<template>
  <div class="search-suggestion-container">
    <van-cell-group>
      <van-cell
        v-for="(item, index) in suggestionList"
        icon="search"
        :key="index"
        @click="$emit('search-suggestion', item)"
      >
        <div slot="title" v-html="highLight(item)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
// 加载第三方库 处理函数防抖问题
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  props: {
    searchValue: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestionList: []
    }
  },
  watch: {
    searchValue: {
      handler: debounce(async function(q) {
        const { data } = await getSearchSuggestion(q)
        console.log(data)
        this.suggestionList = data.data.options
      }, 500),
      immediate: true
    }
  },
  computed: {},
  methods: {
    highLight(val) {
      return val.replace(
        // 这里拼接 正则表达式不太好弄，改用 new 创建正则表达式对象的方法
        new RegExp(this.searchValue, 'gi'),
        `<span style="color:red;">${this.searchValue}</span>`
      )
    }
  }
}
</script>

<style></style>
